package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"news01/models"
)

type NewsController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewsController) List() {
	allnew := []models.News{}
	err := models.DB.Find(&allnew).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: nil,
		}
	}

}
func (c *NewsController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	fl := c.GetString("fl")
	allnew := models.News{
		Title: title,
		Time:  time,
		Fl:    fl,
	}
	err := models.DB.Create(&allnew).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
	}
}
func (c *NewsController) Up() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	time := c.GetString("time")
	fl := c.GetString("fl")
	allnew := models.News{
		Id:    id,
		Title: title,
		Time:  time,
		Fl:    fl,
	}
	err := models.DB.Save(&allnew).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
	}
}
func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.News{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
	}
}
